package com.fire.threadpool.nameThreadFactory;

import com.fire.threadpool.timeRecordThreadPoolExecutor.TimeRecordThreadPoolExecutor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * NameThreadFactoryTest
 *
 * @author zwd
 * @date 2022/3/23
 * @desc
 */
public class NameThreadFactoryTest {
    public static void main(String[] args) {
        TimeRecordThreadPoolExecutor threadPool = null;
        try {
            threadPool = new TimeRecordThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingDeque<Runnable>(), new NameThreadFactory("test"));
            ArrayList<TestCallable> tasks = new ArrayList<>();

            for (int i = 0; i < 100; i++) {
                tasks.add(new TestCallable());
            }

            List<Future<Long>> futures = threadPool.invokeAll(tasks);

            for (Future<Long> future : futures) {
                System.out.println(" - " + future.get());
            }

        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            assert threadPool != null;
            threadPool.shutdown();
        }

    }

    static class TestCallable implements Callable<Long> {

        @Override
        public Long call() throws Exception {
            long total = 0 ;
            for (int i = 0 ; i < 100 ; i++) {
                long now = getRandom();
                total += now;
            }
            Thread.sleep(total);
            return total;
        }

        public long getRandom () {
            return Math.round(Math.random() * 10);
        }
    }
}
